package controller

import (
	"ginfast/api/mall/dto"
	"ginfast/api/mall/model"
	"ginfast/pkg/ctx"
	"ginfast/pkg/orm"
	"ginfast/util"

	"github.com/gin-gonic/gin"
)

// User 分类
type User struct {
}

// ListHandler 列表
func (o *User) ListHandler(c *gin.Context) {
	var data []model.User
	if err := orm.DbFind(&data); err != nil {
		ctx.JSONWriteError(err, c)
		return
	}
	ctx.JSONWriteData(data, c)
}

// PageHandler 分页
func (o *User) PageHandler(c *gin.Context) {
	var p dto.Where
	if err := c.ShouldBind(&p); err != nil {
		ctx.JSONWriteError(err, c)
		return
	}
	var data []model.User
	total, _ := p.DbModelWhere(&model.User{}).Find(&data)
	ctx.JSONWriteTotal(total, data, c)
}

// GetHandler 查询
func (o *User) GetHandler(c *gin.Context) {
	util.QueryByID(&model.User{}, c)
}

// AddHandler 新增
func (o *User) AddHandler(c *gin.Context) {
	var p model.User
	//获取参数
	if err := c.ShouldBind(&p.UserOpt); err != nil {
		ctx.JSONWriteError(err, c)
		return
	}
	if err := orm.DbCreate(&p); err != nil {
		ctx.JSONWriteError(err, c)
		return
	}
	ctx.JSONWriteData(nil, c)
}

// UpdateHandler 修改
func (o *User) UpdateHandler(c *gin.Context) {
	var p model.User
	//获取参数
	if err := c.ShouldBind(&p.UserOpt); err != nil {
		ctx.JSONWriteError(err, c)
		return
	}
	if err := orm.DbUpdateModel(&p); err != nil {
		ctx.JSONWriteError(err, c)
		return
	}
	ctx.JSONWriteData(nil, c)
}

// UpdateStatusHandler 修改
func (o *User) UpdateStatusHandler(c *gin.Context) {
	var p model.User
	//获取参数
	if err := c.ShouldBind(&p.UserOpt); err != nil {
		ctx.JSONWriteError(err, c)
		return
	}
	if err := orm.DbUpdateFields(&p, "Status"); err != nil {
		ctx.JSONWriteError(err, c)
		return
	}
	ctx.JSONWriteData(nil, c)
}

// DeleteHandler 删除
func (o *User) DeleteHandler(c *gin.Context) {
	util.Deletes(&model.User{}, c)
}

func (o User) Routers(r *gin.RouterGroup) {
	r.GET("/list", o.ListHandler)
	r.GET("/page", o.PageHandler)
	r.GET("/:id", o.GetHandler)
	r.POST("", o.AddHandler)
	r.PUT("", o.UpdateHandler)
	r.PUT("/status", o.UpdateStatusHandler)
}
